package com.knife.bbs.action;

import java.util.Map;

import org.apache.commons.mail.SimpleEmail;

import com.knife.bbs.business.BBSConfig;
import com.knife.bbs.business.BBSUserService;
import com.knife.bbs.domain.Mail;
import com.knife.bbs.object.UserInfo;
import com.knife.util.CommUtil;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class MailAction extends BBSAction {
private BBSUserService userService=BBSUserService.getInstance();
	public Page doInit(WebForm form, Module module) {
		// TODO Auto-generated method stub
		return null;
	}

	public Page doFind(WebForm form, Module module) {
		return module.findPage("/"+skin+"/","send");
	}

	public Page doSend(WebForm form, Module module) {
		String username = CommUtil.null2String(form.get("username")).trim();
		if (!"".equals(username) && username != null) {
			//System.out.println(username);
			UserInfo user = userService.getUserInfoByName(username);
			boolean ret = false;
			if (user != null) {
				String password = user.getPassword();
				Map mails = BBSConfig.getInstance().getMails();
				for (int i = 0; i < mails.size(); i++) {
					try {
						SimpleEmail mail = this.mail2email((Mail) mails
								.get(new Integer(i)), username, password);
						mail.send();
						ret = true;
						break;
					} catch (Exception e) {
						System.out.println("error in sending mail");
						continue;
					}

				}
				if (ret) {
					form.addResult("msg", "密码已发送");
					return module.findPage("/"+skin+"/","main");
				} else {
					form.addResult("msg", "发送失败，请联系管理员");
					return module.findPage("/"+skin+"/","send");
				}
			} else {
				form.addResult("msg", "没有该注册的用户名");
				return module.findPage("/"+skin+"/","send");
			}
		} else {
			form.addResult("msg", "填写注册的用户名");
			return module.findPage("/"+skin+"/","send");
		}
	}

	private SimpleEmail mail2email(Mail mail, String username, String password)
			throws Exception {
		SimpleEmail email = new SimpleEmail();
		String msg = mail.getMsg();
		msg = msg.replaceAll("#username", username);
		msg = msg.replaceAll("#password", password);
		mail.setMsg(msg);
		email.setCharset(mail.getCharset());
		email.setMsg(msg);
		email.setFrom(mail.getFrom());
		email.setSubject(mail.getSubject());
		email.setHostName(mail.getHost());
		return email;
	}

}
